package cn.jn.lhm.netty.part08.chat.handler;

import cn.jn.lhm.netty.part08.chat.message.LoginRequestMessage;
import cn.jn.lhm.netty.part08.chat.message.LoginResponseMessage;
import cn.jn.lhm.netty.part08.chat.service.UserServiceFactory;
import cn.jn.lhm.netty.part08.chat.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/11/1 - 0:01
 **/
@ChannelHandler.Sharable
public class ServerLoginHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        boolean login = UserServiceFactory.getUserService().login(msg.getUsername(), msg.getPassword());
        LoginResponseMessage responseMessage;
        if (login) {
            responseMessage = new LoginResponseMessage(true, "欢迎登录," + msg.getUsername());
            // 获取SessionFactory实例并绑定会话信息
            SessionFactory.getSession().bind(ctx.channel(), msg.getUsername());
        } else {
            responseMessage = new LoginResponseMessage(false, "用户名或密码错误");
        }
        // 从当前处理器直接往前找出栈处理器
        ctx.writeAndFlush(responseMessage);
    }
}
